#include "Listener.h"
#include "Service.h"
#include "ListenerHandler.h"
#include "Connection.h"
using namespace std;
Listener::Listener(std::string ip, int port, Service* service, ListenerHandler* handler)
{
	m_ip = ip;
	m_port = port;
	m_service = service;
	m_handler = handler;
}

void Listener::onAccept(struct evconnlistener *evlistener, evutil_socket_t fd, struct sockaddr* addr, int len, void *ptr) {
	Listener* listener = (Listener*)ptr;
	evutil_make_socket_nonblocking(fd);
	bufferevent* bev = bufferevent_socket_new(listener->m_service->getBase(), fd, BEV_OPT_DEFER_CALLBACKS | BEV_OPT_CLOSE_ON_FREE);
	Connection* connection = new Connection(bev, listener->m_service);
	listener->m_handler->onAccept(connection);
}


bool Listener::startListen()
{
	event_base* base = m_service->getBase();
	sockaddr_in addr = {};
	addr.sin_family = AF_INET;
	addr.sin_port = htons(m_port);
	addr.sin_addr.s_addr = inet_addr(m_ip.c_str());
	m_listener = evconnlistener_new_bind(m_service->getBase(), onAccept, this, LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE, -1,(struct sockaddr*)&addr, sizeof(addr));

	if(m_listener) {
		return true;
	} else {
		return false;
	}
}

void Listener::stopListen()
{
	if(m_listener) {
		evconnlistener_disable(m_listener);
		evconnlistener_free(m_listener);
		m_listener = NULL;
	}	
}
